#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
HLS API接口
提供HLS播放和录制信息查询功能
"""

from fastapi import APIRouter, HTTPException, Depends
from typing import Dict, Any, Optional
import os

from app.services.hls_service import get_hls_service
from app.core.database import SessionLocal
from app.models.task import Task

router = APIRouter()


@router.get("/play/{task_name}")
async def get_hls_play_url(task_name: str) -> Dict[str, Any]:
    """
    获取HLS播放地址
    
    Args:
        task_name: 任务名称
        
    Returns:
        播放地址信息
    """
    try:
        # 构建录制目录路径
        record_dir = f"./recordings/{task_name}"
        
        if not os.path.exists(record_dir):
            raise HTTPException(
                status_code=404, 
                detail=f"录制目录不存在: {record_dir}"
            )
        
        # 获取播放URL
        play_url = hls_service.get_hls_play_url(record_dir)
        
        # 获取录制信息
        record_info = hls_service.get_record_info(record_dir)
        
        return {
            "play_url": play_url,
            "record_info": record_info,
            "status": "ready" if record_info["m3u8_exists"] else "waiting"
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/info/{task_name}")
async def get_record_info(task_name: str) -> Dict[str, Any]:
    """
    获取录制详细信息
    
    Args:
        task_name: 任务名称
        
    Returns:
        录制详细信息
    """
    try:
        record_dir = f"./recordings/{task_name}"
        
        if not os.path.exists(record_dir):
            raise HTTPException(
                status_code=404, 
                detail=f"录制目录不存在: {record_dir}"
            )
        
        record_info = hls_service.get_record_info(record_dir)
        
        return {
            "task_name": task_name,
            **record_info,
            "play_url": f"/recordings/{task_name}/index.m3u8"
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/list")
async def list_recordings() -> Dict[str, Any]:
    """
    列出所有录制
    
    Returns:
        统一格式的录制列表
    """
    try:
        recordings_root = "./recordings"
        recordings = []
        
        if os.path.exists(recordings_root):
            for task_name in os.listdir(recordings_root):
                record_dir = os.path.join(recordings_root, task_name)
                if os.path.isdir(record_dir):
                    record_info = hls_service.get_record_info(record_dir)
                    recordings.append({
                        "task_name": task_name,
                        **record_info,
                        "play_url": f"/recordings/{task_name}/index.m3u8"
                    })
        
        # 返回统一格式
        return {
            "code": 200,
            "data": {
                "items": recordings,
                "total": len(recordings)
            },
            "message": "success"
        }
        
    except Exception as e:
        return {
            "code": 500,
            "data": {
                "items": [],
                "total": 0
            },
            "message": f"获取录制列表失败: {str(e)}"
        }


@router.get("/task/{task_id}/play")
async def get_task_hls_url(task_id: int) -> Dict[str, Any]:
    """
    根据任务ID获取HLS播放地址
    
    Args:
        task_id: 任务ID
        
    Returns:
        播放地址信息
    """
    try:
        with SessionLocal() as db:
            task = db.query(Task).filter(Task.id == task_id).first()
            if not task:
                raise HTTPException(status_code=404, detail="任务不存在")
            
            record_dir = f"./recordings/{task.name}"
            play_url = hls_service.get_hls_play_url(record_dir)
            record_info = hls_service.get_record_info(record_dir)
            
            return {
                "task_id": task_id,
                "task_name": task.name,
                "play_url": play_url,
                "record_info": record_info,
                "status": task.status.value
            }
            
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


# 使用单例模式获取服务实例
hls_service = get_hls_service()